import axios from 'axios' 
import { ElMessage } from 'element-plus'  
import pinia from '../stores/store'
import { useUserStore } from '../stores/user'
import NProgress from 'nprogress'
 
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000,
}) 
 

//请求拦截器
service.interceptors.request.use(
  config => {   
    NProgress.start()
    const store = useUserStore(pinia)
    if(store.token){
        config.headers.Authorization = `Bearer ${store.token}`
    }  
    return config // 必须返回配置
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => { 
    NProgress.done()
    const { code, message, data } = response.data
    //   要根据success的成功与否决定下面的操作
    if (code == 200) { 
      return data
    }else{
      if(code == 401){
        const store = useUserStore(pinia)
        ElMessage.error('登录过期，请重新登录')
        store.loginOut()
      }
      ElMessage.error(message)
      return Promise.reject(new Error(message))
    } 
  },
  error => {  
    if(error.response.status == 401){
      ElMessage.error('登录过期，请重新登录')
      useUserStore(pinia).logout()
      return Promise.reject(new Error('登录过期，请重新登录'))
    }
    NProgress.done()
    ElMessage.error(error) // 提示错误信息
    return Promise.reject(error)
  }
)

export default service
